import api from './axios'

// 角色管理相关API
export const roleService = {
  // 获取角色列表
  getRoles: async () => {
    try {
      const response = await api.get('/roles/')
      return {
        data: response.data.results || [],
        total: response.data.count || 0,
        next: response.data.next,
        previous: response.data.previous
      }
    } catch (error) {
      console.error('Failed to get roles:', error)
      throw error
    }
  },
  
  // 获取单个角色详情
  getRole: async (id) => {
    try {
      const response = await api.get(`/roles/${id}/`)
      return response.data
    } catch (error) {
      console.error(`Failed to get role ${id}:`, error)
      throw error
    }
  },
  
  // 创建角色
  createRole: async (roleData) => {
    try {
      const response = await api.post('/roles/', roleData)
      return response.data
    } catch (error) {
      console.error('Failed to create role:', error)
      throw error
    }
  },
  
  // 更新角色
  updateRole: async (id, roleData) => {
    try {
      const response = await api.put(`/roles/${id}/`, roleData)
      return response.data
    } catch (error) {
      console.error(`Failed to update role ${id}:`, error)
      throw error
    }
  },
  
  // 删除角色
  deleteRole: async (id) => {
    try {
      await api.delete(`/roles/${id}/`)
      return true
    } catch (error) {
      console.error(`Failed to delete role ${id}:`, error)
      throw error
    }
  },
  
  // 批量删除角色
  deleteRoles: async (roleIds) => {
    try {
      const promises = roleIds.map(id => api.delete(`/roles/${id}/`))
      await Promise.all(promises)
      return true
    } catch (error) {
      console.error('Failed to delete roles:', error)
      throw error
    }
  },
  
  // 分配角色权限
  assignPermissions: async (roleId, permissionIds) => {
    try {
      const response = await api.post(`/roles/${roleId}/permissions/`, {
        permission_ids: permissionIds
      })
      return response.data
    } catch (error) {
      console.error(`Failed to assign permissions to role ${roleId}:`, error)
      throw error
    }
  },
  
  // 获取角色权限
  getRolePermissions: async (roleId) => {
    try {
      const response = await api.get(`/roles/${roleId}/permissions/`)
      return response.data
    } catch (error) {
      console.error(`Failed to get permissions for role ${roleId}:`, error)
      throw error
    }
  }
} 